import React, {useContext} from 'react';
import {View, Image, Alert, Platform, ScrollView, FlatList} from 'react-native';
import dayjs from 'dayjs';
import Toast from 'react-native-root-toast';
import {useNavigation} from '@react-navigation/native';
import {useMount, useUnmount, useSafeState} from 'ahooks';
import {Text, Button, Input, Dialog, ListItem, Avatar} from '@rneui/themed';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import {useSelector, useDispatch} from 'react-redux';
import GlobalContext from '@/GlobalContext';
import ImagePicker from 'react-native-image-crop-picker';
import fileExtension from 'file-extension';
import {ApiHost, OssHost} from '@/config/common';
import {setKeyGetAccountInfo} from '@/store';
import DocumentPicker from 'react-native-document-picker';
import getDirsInfoSystem from './getDirsInfoSystem';

const leftIconSize = 18;
const rightIconSize = 20;

import RNFS from 'react-native-fs';
import RNFetchBlob from 'react-native-blob-util';
import {Dirs, FileSystem} from 'react-native-file-access';
import putFileToOss from '@/fun/putFileToOss';
import globalStyle from '@/style/global.less';
import {round} from 'lodash';
import updateDirTree from './updateDirTree';
export default ({item = {}, setOpenDirPath}) => {
  const {localMongoDbFileSystem} = useContext(GlobalContext);
  const navigation = useNavigation();
  const dispatch = useDispatch();
  const token = useSelector(state => state.token.value);
  const accountInfo = useSelector(state => state.accountInfo.value);
  let defaultUri = accountInfo?.j_ext_info?.photo_relative_path;
  if (defaultUri) {
    defaultUri = `${OssHost}/${defaultUri}`;
  }
  const [checkedStatus, setCheckedStatus] = useSafeState('');
  const [info, setInfo] = useSafeState({});

  const setBasicInfo = async () => {
    // const sonDocs = await getDirsInfoSystem({pPath: item.path});
    // const sonTotal = sonDocs.length;
    // setInfo({
    //   son_total: sonTotal,
    // });
    const db = localMongoDbFileSystem;
    const dirDocInfo = await db.findOneAsync({path: item.path});
    if (!dirDocInfo) {
      const sonDocs = await getDirsInfoSystem({pPath: item.path});
      const sonTotal = sonDocs.length;
      setInfo({
        son_total: sonTotal,
      });
    }
    if (['Movies'].includes(item.filename)) {
      console.log('dirDocInfo', dirDocInfo);
    }

    // const getNewCkStatus = async () => {
    //
    //   if (sonTotal === 0) {
    //     const doc = await db.findOneAsync({path: item.path});
    //     if (doc?.checked) {
    //       return 'All';
    //     } else {
    //       return '';
    //     }
    //   } else {
    //     const searchText = `^${item.path}/`;
    //     const regex = new RegExp(searchText, 'i');
    //     const hasCkCount = await db.countAsync({path: regex, checked: true});
    //     const notCkCount = await db.countAsync({path: regex, checked: false});

    //     if (['Movies'].includes(item.filename)) {
    //       console.log(
    //         'sonTotal',
    //         sonTotal,
    //         'hasCkCount',
    //         hasCkCount,
    //         'notCkCount',
    //         notCkCount,
    //       );
    //     }

    //     if (hasCkCount > 0 && notCkCount > 0) {
    //       return 'Part';
    //     }
    //   }
    // };
    // const newCkStatus = await getNewCkStatus();
    // setCheckedStatus(newCkStatus);
  };

  const checked = ['All', 'Part'].includes(checkedStatus);

  useMount(async () => {
    try {
      await setBasicInfo();
    } catch (e) {
      console.log('异常', e.message);
    }
  });

  useMount(async () => {});

  let checkedColor = '#40a9ff';
  if (checkedStatus === 'Part') {
    checkedColor = '#999';
  }

  return (
    <ListItem
      onPress={() => {
        // if (checkedStatus === 'All') {
        //   setOpenDirPath(item.path);
        // }
        setOpenDirPath(item.path);
      }}
      style={{
        marginTop: 2,
      }}>
      <ListItem.CheckBox
        checked={checked}
        onPress={e => {
          let newCkStatus = '';
          if (checkedStatus === 'All') {
            newCkStatus = '';
          } else {
            newCkStatus = 'All';
          }
          setCheckedStatus(newCkStatus);
          updateDirTree({
            fileInfo: item,
            db: localMongoDbFileSystem,
            dirPath: item.path,
            checkedStatus: newCkStatus,
          });
        }}
        size={40}
        checkedColor={checkedColor}
      />
      <ListItem.Content>
        <View
          onPress={() => {
            console.log(Math.random());
          }}>
          <ListItem.Title>
            <FontAwesome5 name="folder" size={leftIconSize} /> {item.filename}
          </ListItem.Title>
          <Text style={{color: '#999999'}}>{info.son_total} 子目录</Text>
        </View>
      </ListItem.Content>
      {checkedStatus === 'All' && <Text>全选</Text>}
      {checkedStatus === 'Part' && <Text>部分选</Text>}
      {/* {checkedStatus !== 'All' && <ListItem.Chevron size={rightIconSize} />} */}
      <ListItem.Chevron size={rightIconSize} />
    </ListItem>
  );
};
